package com.vv.vv_commonlibrary.widget;

import android.content.Context;
import android.content.res.TypedArray;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.vv.vv_commonlibrary.R;
import com.vv.vv_commonlibrary.utils.IntPutFilter;

import static android.view.Gravity.BOTTOM;
import static android.view.Gravity.CENTER_VERTICAL;
import static android.view.Gravity.LEFT;
import static android.view.Gravity.RIGHT;

/**
 * 限制数量的EditText输入框
 *
 * @author xia
 */
public class LimitEditText extends FrameLayout {

    private EditText editText;
    private TextView showLength;
    private int maxLength = 200;
    private int minHeight;
    private OnEditTextChangeListener onEditTextChangeListener;
    private ImageView ivDelete;

    public void setOnEditTextChangeListener(OnEditTextChangeListener onEditTextChangeListener) {
        this.onEditTextChangeListener = onEditTextChangeListener;
    }

    public LimitEditText(@NonNull Context context) {
        this(context, null);
    }

    public LimitEditText(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initView(context,attrs);
    }

    private void initView(Context context,AttributeSet attrs) {
        // Load attributes
        final TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.LimitEditText);
        String hintStr = a.getString(R.styleable.LimitEditText_inputHint);
        maxLength = a.getInt(R.styleable.LimitEditText_maxLimitCount, maxLength);
        minHeight = a.getInt(R.styleable.LimitEditText_minH, minHeight);
        int countColor = a.getColor(R.styleable.LimitEditText_countcolor, ContextCompat.getColor(getContext(), R.color.color_999999));
        int countLayout = a.getInt(R.styleable.LimitEditText_countlayout, 0);
        a.recycle();

        LayoutInflater.from(getContext()).inflate(R.layout.limit_edit_text, this);
        editText = findViewById(R.id.editText);
        editText.setHint(hintStr);
        editText.setMinHeight(minHeight);
        //限制最大输入数量
        editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(maxLength)});
        showLength = findViewById(R.id.showLength);
        ivDelete = findViewById(R.id.iv_delete);
        showLength.setTextColor(countColor);
        if (countLayout == 1){
            FrameLayout.LayoutParams layoutParams = (LayoutParams) showLength.getLayoutParams();
            layoutParams.gravity = LEFT | CENTER_VERTICAL;
            showLength.setLayoutParams(layoutParams);
        }
        showInputLength(0);
        IntPutFilter.intPutFilter_no(context,editText);
        editText.addTextChangedListener(new TextWatcher() {
            private CharSequence wordNum;//记录输入的字数
            private int selectionStart;
            private int selectionEnd;

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                wordNum = s;//实时记录输入的字数
            }

            @Override
            public void afterTextChanged(Editable s) {
                int length = wordNum.length();
                if (maxLength <= wordNum.length()) {
                    length = maxLength;
                }
                selectionStart = editText.getSelectionStart();
                selectionEnd = editText.getSelectionEnd();
                if (wordNum.length() > maxLength) {
                    //删除多余输入的字（不会显示出来）
                    s.delete(selectionStart - 1, selectionEnd);
                    editText.setText(s);
                    editText.setSelection(editText.getText().toString().trim().length());//设置光标在最后
                }
                showInputLength(length);
                if (onEditTextChangeListener != null) {
                    onEditTextChangeListener.onEditTextChanged(s.toString().trim());
                }
            }
        });
        editText.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                //触摸的是EditText并且当前EditText可以滚动则将事件交给EditText处理；否则将事件交由其父类处理
                if ((v.getId() == R.id.editText && canVerticalScroll(editText))) {
                    v.getParent().requestDisallowInterceptTouchEvent(true);
                    if (event.getAction() == MotionEvent.ACTION_UP) {
                        v.getParent().requestDisallowInterceptTouchEvent(false);
                    }
                }
                return false;
            }
        });
    }

    /**
     * EditText竖直方向是否可以滚动
     *
     * @param editText 需要判断的EditText
     * @return true：可以滚动   false：不可以滚动
     */
    private boolean canVerticalScroll(EditText editText) {
        //滚动的距离
        int scrollY = editText.getScrollY();
        //控件内容的总高度
        int scrollRange = editText.getLayout().getHeight();
        //控件实际显示的高度
        int scrollExtent = editText.getHeight() - editText.getCompoundPaddingTop() - editText.getCompoundPaddingBottom();
        //控件内容总高度与实际显示高度的差值
        int scrollDifference = scrollRange - scrollExtent;

        if (scrollDifference == 0) {
            return false;
        }

        return (scrollY > 0) || (scrollY < scrollDifference - 1);
    }

    private void showInputLength(int currentLength) {
        String showLengthStr = getContext().getString(R.string.showLimitLength, currentLength, maxLength);
        showLength.setText(showLengthStr);
    }

    public interface OnEditTextChangeListener {
        /**
         * 输入数据变化时的回调
         *
         * @param str
         */
        void onEditTextChanged(String str);
    }

    public void setDefaultContent(String content) {
        if (editText != null) {
            editText.setText(content);
        }
    }

    public void showDelete(){
        ivDelete.setVisibility(VISIBLE);
    }

    public ImageView getIvDelete() {
        return ivDelete;
    }

    public EditText getEditText() {
        return editText;
    }


}
